<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { bookAPI } from '@/api/book'
import { useRouter } from 'vue-router'
import AddToCart from '@/components/AddToCart.vue'

interface Book {
  bookId: number;    // 实际接口返回字段
  bookName: string;  // 实际接口返回字段
  author: string;
  price: string;
  stock: string;
  description?: string;
  coverImage?: string | null;
}

const placeholderImage = 'https://tse1-mm.cn.bing.net/th/id/OIP-C.yzK1RU3WRX1YA0VHe-bsDAAAAA?pid=ImgDet&w=450&h=300&rs=1';
const router = useRouter()
const route = useRoute()
const book = ref<Book | null>(null)

const fetchBookDetail = async () => {
  try {
    const res = await bookAPI.getBookDetail(Number(route.params.id))
    // 转换字段名（如果需要）
    book.value = {
      ...res.data,
      id: res.data.bookId,    // 适配前端使用的字段名
      title: res.data.bookName // 适配前端使用的字段名
    }
  } catch (error) {
    console.error('获取图书详情失败:', error)
  }
}

onMounted(() => {
  fetchBookDetail()
})
</script>

<template>
  <div class="book-detail" v-if="book">
    <el-button @click="router.back()">返回列表</el-button>
    <div class="detail-container">
      <div class="cover">
        <el-image :src="book.coverImage || placeholderImage" />
      </div>
      <div class="info">
        <h2>{{ book.bookName }}</h2>  <!-- 使用转换后的字段名 -->
        <p>作者: {{ book.author }}</p>
        <p>价格: ¥{{ Number(book.price).toFixed(2) }}</p>
        <p>库存: {{ book.stock }}本</p>
        <div class="book-actions">
          <AddToCart :book-id="book.bookId" :book-name="book.bookName" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.book-detail {
  padding: 20px;
}

.back-btn {
  margin-bottom: 20px;
}

.detail-container {
  display: flex;
  gap: 40px;
  margin-top: 20px;
}

.cover {
  flex: 0 0 300px;
}

.info {
  flex: 1;
}

.author, .price, .stock {
  margin: 10px 0;
  color: #666;
}

.description {
  margin-top: 30px;
  line-height: 1.6;
}

.book-actions {
  margin-top: 20px;
}
</style>
